#!/bin/bash
#mount | grep /opt/datastore > /dev/null
#/bin/mount -t nfs,nfs4 | grep "^.* on /opt/datastore type nfs.*$" > /dev/null 2>&1
#if [ $? -ne 0 ]; then
#  logger -t db_backup -p user.err "DB backup not started as datastore is not not mounted"
#  exit 1
#fi

if [ ! -d /opt/datastore/db/backups ]; then
  logger -t db_backup -p user.err "DB backup not started as db backup directory does not exist"
  exit 1
fi
  
dateStr=`date +%Y%m%d%H%M`
backup_folder=/opt/datastore/db/backups/${dateStr}
mysql_bkp_folder="${backup_folder}/mysql"
mongo_bkp_folder="${backup_folder}/mongo"
mkdir -p ${backup_folder} ${mongo_bkp_folder} ${mysql_bkp_folder}
if [ $? -ne 0 ]; then
  logger -t db_backup -p user.err "DB backup not started as failed to create backup directory"
  rm -fr backup_folder
  exit 1
fi

mysqldump -uroot -pxAVa6Aze msp > ${mysql_bkp_folder}/msp.sql --single-transaction
ECODE1=$?
if [ $ECODE1 -ne 0 ]; then
  logger -t db_backup -p user.err "DB backup failed for msp database - $ECODE1"
  rm -fr backup_folder
  exit 1
else
  logger -t db_backup -p user.err "msp DB Dump Successfully completed"
fi

mysqldump -uroot -pxAVa6Aze msp_report > ${mysql_bkp_folder}/msp_report.sql --single-transaction
ECODE2=$?
if [ $ECODE2 -ne 0 ]; then
  logger -t db_backup -p user.err "DB backup failed for msp_report database - $ECODE2"
  rm -fr backup_folder
  exit 1
else
  logger -t db_backup -p user.err "msp_report DB Dump Successfully completed"
fi

mysqldump -uroot -pxAVa6Aze msp_mon > ${mysql_bkp_folder}/msp_mon.sql --single-transaction
ECODE3=$?
if [ $ECODE3 -ne 0 ]; then
  logger -t db_backup -p user.err "DB backup failed for msp_mon database - $ECODE3"
  rm -fr backup_folder
  exit 1
else
  logger -t db_backup -p user.err "msp_mon DB Dump Successfully completed"
fi


echo "Taking backup for mongo databases"
/usr/bin/mongodump --out ${mongo_bkp_folder}
ECODE4=$?
if [ $ECODE4 -ne 0 ]; then
  logger -t db_backup -p user.err "Mongo DB backup failed - $ECODE4"
  rm -fr backup_folder
  exit 1
else
  logger -t db_backup -p user.err "Mongo DB backup Successfully completed"
fi

if [ -f /home/admin/conf/admin.properties ]; then
  retentionStr=`/bin/grep backup_retention_count /home/admin/conf/admin.properties | sed -e 's/backup_retention_count=//g'`
else
  retentionStr=10
fi

# Remove all backup other than value configured, if no values present default policy is 10 backups.
cd /opt/datastore/db/backups/
find . -maxdepth 1 -regex './[0-9]+$' -type d | sed 's:^\./::' | sort -n | head -n -${retentionStr} | tr '\n' '\0' | xargs -r0 rm -fr

